package JUC.A1B2C3;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @className: SolutionCondition
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/9/16 14:09
 */
public class SolutionSingleCondition {
    public static boolean which = false ;
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        char[] aI = "123456".toCharArray();
        char[] aC = "ABCDEF".toCharArray();
        Thread t1 = new Thread(() -> {
            lock.lock();
            try{
                for(char a : aI){
                    while(which){
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(a);
                    which = !which ;
                    condition.signal();
                }
                condition.signal();
            }finally {
                lock.unlock();
            }
        });
        Thread t2 = new Thread(() -> {
            lock.lock();
            try{
                for(char a : aC){
                    while(!which){
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(a);
                    which = !which ;
                    condition.signal();
                }
                condition.signal();
            }finally{
                lock.unlock();
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
